﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;

namespace CitrixPVSWrapper
{

    [System.Management.Automation.Cmdlet("Run", "PvsSetupConnection", SupportsShouldProcess = true)]
    public class Run_PvsSetupConnection : System.Management.Automation.PSCmdlet
    {
        [Parameter(Mandatory = false)]
        public String Server;

        [Parameter(Mandatory = false)]
        public Int32 Port = 54321;

        [Parameter(Mandatory = false)]
        [ValidateNotNullOrEmpty]
        public PSCredential ConnectionCredentials;

        protected override void ProcessRecord()
        {
            // Verbose and Debug Settings
            Boolean Verbose = this.MyInvocation.BoundParameters.ContainsKey("Verbose");
            WriteVerbose("Verbose Flag: " + Verbose);
            Boolean Debug = this.MyInvocation.BoundParameters.ContainsKey("Debug");
            WriteDebug("Debug Flag: " + Debug);

            // Collections to hold the queries and the results
            string TargetObject = "SetupConnection";

            //Build the query object
            QueryDefinition RunQuery = new QueryDefinition(QueryActionType.Run, TargetObject);

            if (MyInvocation.BoundParameters.ContainsKey("Server")) { RunQuery.Parameters.Add("server=\"" + Server + "\""); };
            if (MyInvocation.BoundParameters.ContainsKey("Port")) { RunQuery.Parameters.Add("port=\"" + Port + "\""); };
            if (MyInvocation.BoundParameters.ContainsKey("ConnectionCredentials")) 
            {
                RunQuery.RecordValues.Add("User=\"" + this.ConnectionCredentials.UserName + "\"");
                RunQuery.RecordValues.Add("Password=\"" + PvsHelpers.ConvertToUnsecureString(this.ConnectionCredentials.Password) + "\""); 
            }

            string ShouldProcessMessage = "Setup a connection to the PVS server";
           
            // Perform the actual Run and return any errors
            if (ShouldProcess(ShouldProcessMessage))
            {
                MCliReturnObject Return = PvsHelpers.ExecuteMcliAction(RunQuery, Verbose, Debug);
                if (Return.ReturnState == ReturnState.Error) { foreach(ErrorRecord Error in Return.Errors) { WriteError(Error); } }
            }
        }
    }
}
